package com.boarsoft.config.spring;

import java.util.Map;
import java.util.ServiceLoader;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.boarsoft.config.annotation.PropConfig;
import com.boarsoft.config.manager.PropConfigManager;
import com.boarsoft.config.plugin.ConfigPlugin;

/**
 * spring启动初始化配置类服务
 *
 */
public class ConfigBoot implements ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 搜集带了注解的配置类
		initConfProp(event);
		// 通过SPI定义不同的插件扩展进行初始化
		for (ConfigPlugin configPlugin : ServiceLoader.load(ConfigPlugin.class)) {
			configPlugin.init();
		}
	}

	public void initConfProp(ContextRefreshedEvent event) {
		Map<String, Object> propbeans = event.getApplicationContext().getBeansWithAnnotation(PropConfig.class);
		for (Object bean : propbeans.values()) {
			String group = bean.getClass().getAnnotation(PropConfig.class).group();
			if (group != null && !"".equals(group)) {
				PropConfigManager.addResource(group, bean);
			} else {
				PropConfigManager.addResource(bean.getClass().getName(), bean);
			}
		}
	}
}
